package com.integral.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.integral.constant.DeclarationConstant;
import com.integral.util.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.integral.biz.IDeclarationBiz;
import com.integral.entity.UserInfo;
import com.integral.util.UploadImgUtil;
import com.integral.vo.DeclarationVo;
import org.weixin4j.misc.BASE64Encoder;

@Controller
@RequestMapping("/declaration")
public class DeclarationController {
	protected final Log logger = LogFactory.getLog(getClass());
	@Resource
	private IDeclarationBiz declarationBiz;
	
	/**
	 * 查询报单信息列表
	 * @param declarationVo
	 * @return
	 */
	@RequestMapping(value="/findDeclaration")
	@ResponseBody
	public Map<String, Object> findDeclaration(DeclarationVo declarationVo){
		//查询未删除的数据
		declarationVo.setDeleteFlag(0);
		List<DeclarationVo> list = declarationBiz.findDeclaration(declarationVo);
		
		Map<String, Object> map = new HashMap<String, Object>();
		Long total = declarationBiz.findDeclarationCount(declarationVo);
		map.put("total", total == null ? 0 : total);
		map.put("rows", list);
		return map;
	}
	
	/**
	 * 审核报单
	 */
	@RequestMapping(value="/auditDeclaration")
	@ResponseBody
	public String auditDeclaration(HttpServletRequest request, HttpServletResponse response,DeclarationVo declarationVo){
		//获取登录对象
		HttpSession session = request.getSession();
		UserInfo user = (UserInfo)session.getAttribute("userInfo");
		//设置修改人名
		declarationVo.setUpdateEmp(user.getUserName());
		int i = declarationBiz.auditDeclaration(declarationVo);
		switch (i) {
		case 1:
			return "审核成功!";
		case -1:
			return "审核失败,订单信息不全!";
		case -2:
			return "审核失败,找不到银行汇率!";
		case -3:
			return "审核失败,找不到余额记录!";
		case -4:
			return "审核失败,找不到上级用户!";
		case -5:
			return "审核失败,找不到结算关系!";
		default:
			break;
		}
		return "management/declaration";
	}
	/**
	 * 驳回报单
	 * @return
	 */
	@RequestMapping(value="/auditFile")
	@ResponseBody
	public String auditFile(DeclarationVo declarationVo,HttpServletRequest request){
		//获取登录对象
		HttpSession session = request.getSession();
		UserInfo user = (UserInfo)session.getAttribute("userInfo");
		//设置修改人名
		declarationVo.setUpdateEmp(user.getUserName());
		declarationBiz.auditFile(declarationVo);
		return "management/declaration";
	}
	
	/**
	 * 人工报单
	 * @param declarationVo
	 * @return
	 */
	@RequestMapping(value="/artificialDeclaration")
	@ResponseBody
	public String artificialDeclaration(DeclarationVo declarationVo,HttpServletRequest request, HttpServletResponse response){
		String msg = null;
		try {
			//获取登录对象
			HttpSession session = request.getSession();
			UserInfo user = (UserInfo)session.getAttribute("userInfo");
			//设置修改人名
			declarationVo.setUpdateEmp(user.getUserName());
			//上传文件
			if(null != declarationVo.getUploadImgs() && declarationVo.getUploadImgs().length > 0){
				MultipartFile[] files = declarationVo.getUploadImgs();
				String fileName = "";
				for (MultipartFile multipartFile : files) {
					String img = UploadImgUtil.dowloadFile(multipartFile, request);
					fileName += img+";";
				}
				if(StringUtils.isNotEmpty(fileName)){
					declarationVo.setDeclarationImg(fileName);
				}else{
					declarationVo.setDeclarationImg(null);
				}
			}
			int temp = declarationBiz.artificialDeclaration(declarationVo);
			if(temp>0){
				msg = "报单成功！";
			}else{
				msg = "报单失败！";
			}
		} catch (Exception e) {
			msg = "报单失败！";
			logger.error("人工报单异常",e);
		}
		
		return msg;
	}

	/**
	 * t打开图片
	 * @param declarationVo
	 * @return
	 */
	@RequestMapping(value="/openImage")
	@ResponseBody
	public Object openImage(String imageName,HttpServletRequest request, HttpServletResponse response) throws IOException {
		String[] split = imageName.split(";");
		ArrayList<String> json = new ArrayList<>();
		for (int i = 0; i<split.length;i++) {
			if(StringUtils.isNotEmpty(split[i])){
				File file = new File(DeclarationConstant.UPLOAD_FILEPATH + File.separator + split[i]);
				InputStream in = null;
				byte[] data = null;
				//读取图片字节数组
				try {
					in = new FileInputStream(file);
					data = new byte[in.available()];
					in.read(data);
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				//对字节数组Base64编码
				BASE64Encoder encoder = new BASE64Encoder();
				json.add("data:image/png;base64," + URLEncoder.encode(encoder.encode(data)));
			}
		}
		return json;
	}
	
	/**
	 * 获取当前未审核报单的数量
	 * @return
	 */
	@RequestMapping(value="/unreviewedNum")
	@ResponseBody
	public Long unreviewedNum(){
		DeclarationVo declarationVo = new DeclarationVo();
		declarationVo.setStart(null);
		declarationVo.setPageSize(null);
		declarationVo.setPageNum(null);
		declarationVo.setStatus(0);
		return declarationBiz.findDeclarationCount(declarationVo);
	}
}
